import json
import time
from datetime import datetime
from contextlib import asynccontextmanager
from fastapi import FastAPI, Depends
from sqlmodel import Session
from starlette.requests import Request
from starlette.staticfiles import StaticFiles
from starlette.templating import Jinja2Templates
from plugin.database import create_engine_and_tables, engine
from routers.api import api_router
from models.logs import HttpLog
from plugin.backgrouds import scheduler

@asynccontextmanager
async def lifespan(app: FastAPI):
    print("开启服务")
    try:
        # 创建数据库和表
        create_engine_and_tables()
        print("数据库创建成功")
        scheduler.start()
    except Exception as e:
        print("数据库创建失败")
        print(e)
    yield
    scheduler.shutdown()
    print("关闭服务")


app = FastAPI(
    title="FastAPI",
    description="FastAPI",
    version="0.0.1",
    lifespan=lifespan
)
# 配置静态文件目录
app.mount("/static", StaticFiles(directory="static"), name="static")
# 配置Jinja2模板引擎
templates = Jinja2Templates(directory="templates")
app.include_router(api_router)


@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    start_time = time.time()
    response = await call_next(request)
    process_time = time.time() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    logs = {
        'start_time': time.time(),
        'process_time': process_time,
        'status_code': response.status_code,
        'path': request.url.path,
        'method': request.method,
        'query_params': dict(request.query_params),
        'client': request.client.host,
        'ip': request.client.host,
        'user_agent': request.headers.get('user-agent'),
        'referer': request.headers.get('referer')
    }
    http_log = HttpLog(logs=json.dumps(logs))
    with Session(engine) as session:
        session.add(http_log)
        session.commit()
    return response


if __name__ == '__main__':
    import uvicorn
    uvicorn.run("main:app", host="127.0.0.1", port=8000, reload=True)
